using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;

namespace Livestock.Recommendation
{
    delegate void UpdateControlDelegate(string text);

    public class ThreadSearcher
    {
        private string url;
        private Control outputControl;

        public ThreadSearcher(string url, Control outputControl)
        {
            this.url = url;
            this.outputControl = outputControl;
        }

        public void startSearch()
        {
            ThreadStart threadStart = new ThreadStart(doSearch);
            Thread searchThread = new Thread(threadStart);
            searchThread.Start();
        }

        private void doSearch()
        {
            string stupidResult = url.ToLower();
            updateControl(stupidResult);
        }

        private void updateControl(string text)
        {
            if (!outputControl.InvokeRequired)
            {
                outputControl.Text = text;
            }
            else
            {
                UpdateControlDelegate updateDelegate = new UpdateControlDelegate(updateControl);
                outputControl.Invoke(updateDelegate, new object[] { text });
                //updateDelegate.Invoke(text);
            }
        }
    }

    public class BGWorkerWrapper
    {
        private string inputString;
        private Control outputControl;
        private string outputString;

        public void doStuff(string s, Control outputControl)
        {
            BackgroundWorker bgWorker = new BackgroundWorker();
            bgWorker.DoWork += doWork;
            bgWorker.RunWorkerCompleted += workComplete;

            inputString = s;
            bgWorker.RunWorkerAsync();
            this.outputControl = outputControl;
        }

        private void doWork(object sender, DoWorkEventArgs args)
        {
            string newString = inputString.ToLower();
            outputString = newString;
        }

        private void workComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            outputControl.Text = outputString;
        }
    }
}